/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.nonmember;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Member;
import model.MemberService;
import model.UserService;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import view.nonmember.forms.RegisterStrutsActionForm;

/**
 *
 * @author SONY
 */
public class RegisterStrutsAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // Use Struts actions to record business processing errors.
        ActionErrors errors = new ActionErrors();
        // Store this set in the request scope, in case we need to send the ErrorPage view.
        saveErrors(request, errors);       
        try {
            RegisterStrutsActionForm register_form = (RegisterStrutsActionForm) form;
            
            MemberService member_service = new MemberService();
            
            String address = register_form.getStreet() + " - " + register_form.getWard() + " - " + register_form.getDistrict() + " - " 
                                + register_form.getCity() + " - " + register_form.getProvince();
            Member member = member_service.addMember(register_form.getFirstName(), register_form.getLastName(), address, register_form.getPhone(), register_form.getGender());
            if (member == null) {
                System.err.println("Can not add member.");
            } else {
                int memberid = member.getMemberID();
                UserService user_service = new UserService();
                if(user_service.addUser(register_form.getEmail(), register_form.getPassword(), memberid)) {
                    return mapping.findForward(SUCCESS);
                }
            }
        } catch(Exception e) {
            System.err.println(e);
        }

        return mapping.findForward("error");
    }
}
